package cn.filter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.controller.BaseController;
import cn.kpi.entity.sys.UserEntity;
public class CommonInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			LoginCheck authPassport = ((HandlerMethod) handler).getMethodAnnotation(LoginCheck.class);
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			BaseController bas = new BaseController();
			if (authPassport == null || authPassport.description() == true) {
				UserEntity user=bas.getWebSysUserAttribute("UserEntity");
				if(user!=null){
					return true;
				}
				else{
					String contentType =httpRequest.getHeader("X-Requested-With");
					if(contentType!=null&&contentType.equals("XMLHttpRequest")){
						httpResponse.addHeader("sessionstatus", "timeout");
						return false;
					}
					else{
						httpResponse.setContentType("text/html;charset=gbk");
						httpResponse.setCharacterEncoding("utf-8");
						httpResponse.setHeader("Cache-Control", "no-cache");
						String html = "<script language='javascript'> alert('登陆超时');top.location='"
								+ request.getContextPath() + "/login';  </script>";
						httpResponse.getWriter().write(html);
						return false;
					}
					
				}
			} else {
				return true;
				
			}
		} else {
			return true;
		}
	}
}
